package net.mihome.app.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.ImageLoader;

import net.mihome.app.AppContext;
import net.mihome.app.R;
import net.mihome.app.bean.Tweet;
import net.mihome.app.bean.net.ResponsePojo;
import net.mihome.app.common.BitmapManager;
import net.mihome.app.common.StringUtils;
import net.mihome.app.common.UIHelper;
import net.mihome.app.ui.TweetDetail;
import net.mihome.app.ui.ViewPagerActivity;
import net.mihome.app.ui.view.MihomeBigPaperView;
import net.mihome.app.utils.EmoticonsUtils;
import net.mihome.app.utils.MiAsyncHttpResponseHandler;
import net.mihome.app.widget.LinkView;
import net.mihome.app.widget.LinkView.OnLinkClickListener;

import org.apache.http.Header;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 动弹Adapter类
 * 
 * @author liux (http://my.oschina.net/liux)
 * @version 1.0
 * @created 2012-3-21
 */
public class ListViewBigpaperAdapter extends MyBaseAdapter {
	private Context context;// 运行上下文
	private List<Tweet> listItems;// 数据集合
	private LayoutInflater listContainer;// 视图容器
	private int itemViewResource;// 自定义项视图源
	private BitmapManager bmpManager;
    private String curUserName=null;
    private ImageLoader imageLoader;
    MihomeBigPaperView mihomeBigPaperView;
    private Integer maxId=-1;   //列表中的最大id
	public static class ListItemView { // 自定义控件集合
		public ImageView userface;
		public TextView username;
		public TextView date;
		public LinkView content;
		public TextView commentCount;
		public TextView client;
		public ImageView image;
        public TextView supportNumView;
        public View supportNumIcon;
        public View supportNumIcon2;
        public ImageView[] images;
        public LinkView commentLinkView;
        public View isTopView;
	}

	/**
	 * 实例化Adapter
	 *
	 * @param context
	 * @param data
	 * @param resource
	 */
	public ListViewBigpaperAdapter(Context context,MihomeBigPaperView mihomeBigPaperView, List<Tweet> data, int resource,ImageLoader imageLoader) {
		this.context = context;
		this.listContainer = LayoutInflater.from(context); // 创建视图容器并设置上下文
		this.itemViewResource = resource;
		this.listItems = data;
        this.imageLoader=imageLoader;
		this.bmpManager = new BitmapManager(BitmapFactory.decodeResource(
				context.getResources(), R.drawable.widget_dface_loading));
        net.mihome.app.bean.User user=AppContext.getInstance().getLoginInfo();
        if(user!=null&&user.getName()!=null){
            curUserName=user.getName();
        }
        this.mihomeBigPaperView=mihomeBigPaperView;
	}

	public int getCount() {
		return listItems.size();
	}

	public Object getItem(int arg0) {
		return listItems.get(arg0);
	}

	public long getItemId(int arg0) {
        return listItems.get(arg0).getId();
	}

	/**
	 * ListView Item设置
	 */
	public View getView(int position, View convertView, ViewGroup parent) {
		// Log.d("method", "getView");

		// 自定义视图
		ListItemView listItemView = null;

		if (convertView == null) {
			// 获取list_item布局文件的视图
			convertView = listContainer.inflate(this.itemViewResource, null);

			listItemView = new ListItemView();
			// 获取控件对象
			listItemView.userface = (ImageView) convertView
					.findViewById(R.id.tweet_listitem_userface);
			listItemView.username = (TextView) convertView
					.findViewById(R.id.tweet_listitem_username);
			listItemView.content = (LinkView) convertView
					.findViewById(R.id.tweet_listitem_content);
			listItemView.image = (ImageView) convertView
					.findViewById(R.id.tweet_listitem_image);
			listItemView.date = (TextView) convertView
					.findViewById(R.id.tweet_listitem_date);
			listItemView.commentCount = (TextView) convertView
					.findViewById(R.id.tweet_listitem_commentCount);
			listItemView.client = (TextView) convertView
					.findViewById(R.id.tweet_listitem_client);
            listItemView.supportNumView= (TextView) convertView.findViewById(R.id.tweet_listitem_like_num);
            listItemView.commentLinkView= (LinkView) convertView.findViewById(R.id.tweet_listitem_comment);
            listItemView.supportNumIcon= (View) convertView.findViewById(R.id.tweet_listitem_like_icon);
            listItemView.supportNumIcon2= (View) convertView.findViewById(R.id.tweet_listitem_like_icon1);
			// 设置控件集到convertView
            //初始化图片列表
            listItemView.images=new ImageView[]{
                    listItemView.image = (ImageView) convertView.findViewById(R.id.tweet_listitem_image),
                    listItemView.image = (ImageView) convertView.findViewById(R.id.tweet_listitem_image1),
                    listItemView.image = (ImageView) convertView.findViewById(R.id.tweet_listitem_image2),
                    listItemView.image = (ImageView) convertView.findViewById(R.id.tweet_listitem_image3),
                    listItemView.image = (ImageView) convertView.findViewById(R.id.tweet_listitem_image4),
                    listItemView.image = (ImageView) convertView.findViewById(R.id.tweet_listitem_image5)
            };
            listItemView.isTopView=convertView.findViewById(R.id.is_tip_view);
			convertView.setTag(listItemView);
		} else {
			listItemView = (ListItemView) convertView.getTag();
		}

		// 设置文字和图片
        Tweet tweet = listItems.get(position);
        if(tweet!=null&&maxId.compareTo(tweet.getId())<0){
            maxId=tweet.getId();
        }
		listItemView.username.setText(tweet.getAuthor());
        if(tweet.getUser()!=null&&tweet.getUser().getMarkName()!=null){
            listItemView.username.setText(tweet.getUser().getMarkName());
        }
		listItemView.username.setTag(tweet);// 设置隐藏参数(实体类)

		// listItemView.content.setText(tweet.getBody());
		// listItemView.content.parseLinkText();
		String body=tweet.getBody();
		body=EmoticonsUtils.filterWechat(body);
		listItemView.content.setLinkText(body);
		listItemView.content.setTag(tweet);// 设置隐藏参数(实体类)
//		listItemView.content.setOnClickListener(linkViewClickListener);
        setLinkViewClickListener(listItemView.content,tweet,position);
		listItemView.content.setLinkClickListener(linkClickListener);
        StringBuffer commentStr=new StringBuffer();
        if(tweet.getCommentList()!=null&&tweet.getCommentList().size()>0){

            Iterator<Map<String,Object>> iterator=tweet.getCommentList().iterator();
            while(iterator.hasNext()){
                Map map=iterator.next();
                commentStr.append("<font color='#0000FF'>").append(map.get("username")).append("</font>").append(":");
                commentStr.append(map.get("text"));
                if(iterator.hasNext()){
                    commentStr.append("<br />");
                }
            }
        }
        if(commentStr==null||commentStr.length()==0){
            listItemView.commentLinkView.setVisibility(View.GONE);
        }else{
            listItemView.commentLinkView.setLinkText(EmoticonsUtils.filterWechat(commentStr.toString()));
            listItemView.commentLinkView.setVisibility(View.VISIBLE);
        }

		listItemView.date.setText(StringUtils.friendly_time(tweet.getPubDate()));
		listItemView.commentCount.setText(tweet.getCommentCount() + "");
        listItemView.supportNumView.setText(tweet.getSupport() + "");
        listItemView.supportNumView.setTag(tweet.getId());
        listItemView.supportNumIcon.setTag(listItemView.supportNumView);
        listItemView.supportNumIcon2.setTag(listItemView.supportNumView);
        listItemView.supportNumIcon.setOnClickListener(supportClickListener);
        listItemView.supportNumIcon2.setOnClickListener(supportClickListener);
        if(tweet.getIsTop()==0){
            listItemView.isTopView.setVisibility(View.VISIBLE);
        }else{
            listItemView.isTopView.setVisibility(View.GONE);
        }
        if(tweet.getSupport_list()!=null&&!"".equals(tweet.getSupport_list())){
            String supportList=tweet.getSupport_list();
            if(supportList.length()>21){
                supportList=supportList.substring(0,21)+"...等点赞";
            }else{
                supportList=supportList+"点赞";
            }
            if(supportList.startsWith(",")){
                supportList=supportList.substring(1);
            }
            listItemView.client.setText(supportList);
        }else{
            listItemView.client.setText("还没有人赞哦");
        }

		String faceURL = tweet.getFace();
		if(faceURL!=null){
			if (faceURL.endsWith("portrait.gif") || StringUtils.isEmpty(faceURL)) {
				listItemView.userface.setImageResource(R.drawable.widget_dface);
			} else {
				bmpManager.loadBitmap(faceURL, listItemView.userface);
//                imageLoader.displayImage(faceURL,listItemView.userface);
			}
		}
		listItemView.userface.setTag(tweet);
        listItemView.userface.setOnClickListener(faceClickListener);

        //批量添加图片
        if(tweet.getImgSmalls()!=null&&tweet.getImgSmalls().length>0){
            for(int i=0;i<listItemView.images.length;i++){
                if(i<tweet.getImgSmalls().length){
//                    imageLoader.displayImage(tweet.getImgSmalls()[i], listItemView.images[i]);
                    bmpManager.loadBitmap(tweet.getImgSmalls()[i], listItemView.images[i]);
                    listItemView.images[i].setOnClickListener(imageClickListener);
//                    listItemView.images[i].setTag(tweet.getImgBigs()[i]);
                    listItemView.images[i].setTag(tweet.getImgBig());
                    listItemView.images[i].setVisibility(ImageView.VISIBLE);
                }else{
                    listItemView.images[i].setVisibility(ImageView.GONE);
                }
            }
        }else{
            for(int i=0;i<listItemView.images.length;i++){
                listItemView.images[i].setVisibility(ImageView.GONE);
            }
        }
		return convertView;
	}

	private View.OnClickListener faceClickListener = new View.OnClickListener() {
		public void onClick(View v) {
			Tweet tweet = (Tweet) v.getTag();
			UIHelper.showUserCenter(v.getContext(), tweet.getAuthorId(),
					tweet.getAuthor(),null);
		}
	};

	private View.OnClickListener imageClickListener = new View.OnClickListener() {
		public void onClick(View v) {
            Intent intent=new Intent(context, ViewPagerActivity.class);
            intent.putExtra("imgurls",(String) v.getTag());
            context.startActivity(intent);
//			UIHelper.showImageZoomDialog(v.getContext(), (String) v.getTag());
		}
	};

    private View.OnClickListener supportClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            View imageView=(View)view;
            final TextView textView= (TextView) imageView.getTag();
            Integer tweetId= (Integer) textView.getTag();
            if(tweetId!=null){
                AppContext.getInstance().supportTweetAsync(tweetId,new MiAsyncHttpResponseHandler() {
                    @Override
                    public void onSuccess(int arg0, Header[] arg1, ResponsePojo responsePojo) {
                        String text=textView.getText().toString();
                        if(text!=null){
                            int addSupport=Integer.valueOf(text);
                            addSupport++;
                            textView.setText(addSupport+"");
                        }
                        Toast.makeText(context,"点赞成功",Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onFailure(int arg0, Header[] arg1, Throwable arg3) {
                        String msg=arg3.getMessage();
                        if(msg==null||"".equals(msg.trim())){
                            msg="点赞失败~稍后再试吧";
                        }
                        Toast.makeText(context,msg,Toast.LENGTH_SHORT).show();

                    }
                });
            }else {
                Toast.makeText(context,"点赞失败~稍后再试吧",Toast.LENGTH_SHORT).show();
            }
        }
    };
    private void setLinkViewClickListener(View view,final Tweet tweet,final int postion){
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(context, TweetDetail.class);
                intent.putExtra("tweet_id", tweet.getId());
                if(context instanceof Activity){
                    Activity mainActivity= (Activity) context;
                    mainActivity.startActivityForResult(intent,postion+1);
                }else{
                    context.startActivity(intent);
                }
            }
        });
    }
//	private View.OnClickListener linkViewClickListener = new View.OnClickListener() {
//		public void onClick(View v) {
//			if (!isLinkViewClick()) {
//				UIHelper.showTweetDetail(v.getContext(),
//						((Tweet) v.getTag()).getId());
//			}
//			setLinkViewClick(false);
//		}
//	};

	private OnLinkClickListener linkClickListener = new OnLinkClickListener() {
		public void onLinkClick() {
			setLinkViewClick(true);
		}
	};

    public Integer getMaxId() {
        return maxId;
    }

    public void setMaxId(Integer maxId) {
        this.maxId = maxId;
    }
    /**
     * 这个函数很简单，找出数据列表中从index为0开始，连续不间断的置顶的帖子的id，拼接成字符串
     * */
    public String getTopIds(){
        StringBuilder stringBuilder=new StringBuilder("");
        if(listItems!=null&&listItems.size()>0){
            for(int i=0;i<listItems.size();i++){
                Tweet tweet=listItems.get(i);
                if(tweet.getIsTop()==0){
                    //如果是置顶，将id添加到字符串中。
                    stringBuilder.append(",").append(tweet.getId());
                }else{
                    //如果不是置顶，直接返回字符串(因为要求是不间断的置顶的帖子的id)
                    return stringBuilder.toString();
                }
            }
        }
        return null;
    }
 }